import { Loading } from 'element-ui'

let instance = null

// 出现loading 延迟
const SHOW_LOADING_DELAY = 1000
// 出现loading 最大时长关闭
const MAX_LOADING_DURATION = 60 * 1000

const debugLog = false

// 先出现遮罩
const maskLoadingOption = {
  // target: '.modules-container',
  lock: true,
  text: null,
  spinner: ' ',
  background: 'rgba(0, 0, 0, 0)'
}

// 延迟出现loading
const showLoadingOption = {
  // target: '.modules-container',
  lock: true,
  // text: '加载中...',
  spinner: '',
  background: 'rgba(0, 0, 0, 0.3)',
  customClass: 'app-loading'
}

class StaticLoading {
  // 静态唯一的loading计数
  // 当为0时 打开loading  小于等于0时 关闭loading
  static currentLoadingCount = 0
  // 只有遮罩的loading 锁定页面
  maskLoading = null

  constructor() {
    return instance || this
  }

  static getInstance() {
    if (!instance) {
      instance = new StaticLoading()
    }
    return instance
  }

  /**
   * 关闭所有loading和计时器
   * @private
   */
  _closeBoth() {
    clearTimeout(this.loadingTimer)
    this.maskLoading && this.maskLoading.close && this.maskLoading.close()
    this.showLoading && this.showLoading.close && this.showLoading.close()
    clearTimeout(this.forceCloseTimer)
    StaticLoading.currentLoadingCount = 0
  }

  /**
   * 当计数为 0 时候 打开loading
   * @private
   */
  _beginLoading() {
    this.maskLoading = Loading.service(maskLoadingOption)
    clearTimeout(this.loadingTimer)
    this.loadingTimer = setTimeout(() => {
      this.maskLoading.close()
      this.showLoading = Loading.service(showLoadingOption)
    }, SHOW_LOADING_DELAY)
  }

  /**
   * 重置强制关闭loading的时间
   * @private
   */
  _resetForceCloseTimer() {
    clearTimeout(this.forceCloseTimer)
    this.forceCloseTimer = setTimeout(() => {
      debugLog && console.log('达到强制loading关闭时间')
      this._closeBoth()
    }, MAX_LOADING_DURATION)
  }

  /**
   * 开始loading 计数加一
   */
  begin() {
    if (StaticLoading.currentLoadingCount === 0) {
      this._beginLoading()
    }
    // 每个请求刷新强制关闭时间
    this._resetForceCloseTimer()
    StaticLoading.currentLoadingCount++
    debugLog && console.log('add', StaticLoading.currentLoadingCount)
  }

  /**
   * 减少一个 loading计数 为0时关闭loading
   */
  end() {
    StaticLoading.currentLoadingCount--
    if (StaticLoading.currentLoadingCount <= 0) {
      this._closeBoth()
    }
    debugLog && console.log('reduce', StaticLoading.currentLoadingCount)
  }
}

export default StaticLoading
